package gee

import (
	"encoding/json"
	"fmt"
	"net/http"
)

//ffds
type H map[string]interface{}

type Context struct {
	Req *http.Request

	Resp http.ResponseWriter

	Method string

	Path string

	StatusCode int
}

// return Context
func NewContext(r *http.Request, w http.ResponseWriter) *Context {
	return &Context{
		Req:    r,
		Resp:   w,
		Path:   r.URL.Path,
		Method: r.Method,
	}
}

// query
func (c *Context) Query(key string) string {
	return c.Req.URL.Query().Get(key)
}

// Get Form
func (c *Context) Form(key string) string {
	return c.Req.FormValue(key)
}

// set Status
func (c *Context) Status(status int) {
	c.StatusCode = status
	c.Resp.WriteHeader(status)
}

//set Header
func (c *Context) SetHeader(key, value string) {
	c.Resp.Header().Set(key, value)
}

//resp string
func (c *Context) String(code int, format string, value ...interface{}) {
	c.SetHeader("Content-Type", "text/plain")
	c.Status(code)
	c.Resp.Write([]byte(fmt.Sprintf(format, value...)))
}

//res json
func (c *Context) Json(code int, data interface{}) {
	c.SetHeader("Content-Type", "application/json")
	c.Status(code)
	encoder := json.NewEncoder(c.Resp)
	if err := encoder.Encode(data); err != nil {
		http.Error(c.Resp, err.Error(), code)
	}
}

//res data
func (c *Context) Data(code int, data []byte) {
	c.Status(code)
	c.Resp.Write(data)
}

//res html
func (c *Context) Html(code int, html string) {
	c.Status(code)
	c.SetHeader("Content-Type", "text/html")
	c.Resp.Write([]byte(html))
}
